package cn.jiadakeji.parent.service.impl;

import cn.jiadakeji.parent.common.constant.RedisPrefixConstants;
import cn.jiadakeji.parent.common.core.redis.RedisCache;
import cn.jiadakeji.parent.domain.SchoolClass;
import cn.jiadakeji.parent.dto.SchoolClassDTO;
import cn.jiadakeji.parent.dto.SchoolDTO;
import cn.jiadakeji.parent.mapper.SchoolClassMapper;
import cn.jiadakeji.parent.service.SchoolClassService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Collections;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author heyanfeng
 * @create 2022-03-09 16:56
 */
@Service
public class SchoolClassServiceImpl extends ServiceImpl<SchoolClassMapper, SchoolClass> implements SchoolClassService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取年级班级
     */
    @Override
    public List<SchoolClassDTO> getSchoolGrade(String schoolId) {
        // TODO:考虑缓存问题
        String data = redisTemplate.opsForValue().get(RedisPrefixConstants.GRADE_CLASS_PREFIX + schoolId);
        if (data != null) {
            return JSON.parseObject(data, new TypeReference<List<SchoolClassDTO>>() {
            });
        } else {
            // 获取班级信息
            List<SchoolClass> classList = baseMapper.selectList(new QueryWrapper<SchoolClass>()
                    .eq("school_id", schoolId));
            // 类型转换
            List<SchoolClassDTO> collect = classList.stream().map(clazz -> {
                SchoolClassDTO schoolClassDTO = new SchoolClassDTO();
                BeanUtils.copyProperties(clazz, schoolClassDTO);
                return schoolClassDTO;
            }).collect(Collectors.toList());
            String jsonString = JSON.toJSONString(collect);
            redisCache.setCacheList(RedisPrefixConstants.GRADE_CLASS_PREFIX+ schoolId ,collect);
            return collect;
        }

    }


}
